//
//  FeelingAddViewController.swift
//  MoodDiary
//
//  Created by TanJian on 2021/12/26.
//

import UIKit
import SVProgressHUD


protocol FeelingAddViewControllerDelegate: AnyObject {
    func refreshUI()
}

private let reuseIdentifier = "FeelingAddCollectionViewCell"
private let cellSpacing: CGFloat = 40
private let cellWH: CGFloat = floor((UIScreen.main.bounds.width - 20*2 - 5*2 - cellSpacing*3) / 4)


class FeelingAddViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {

    @IBOutlet weak var tfBtmView: UIView!
    @IBOutlet weak var nameField: UITextField!
    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var feelingImgCollectionView: UICollectionView!
    @IBOutlet weak var saveBtn: UIButton!
    
//    var imgDict : Dictionary<String,Any> = Dictionary.init()
    var customDict:[String:Any] = [String:Any]()
    var customIndex:Int = 0
    
    weak var feelingAddDelegate:FeelingAddViewControllerDelegate?
    
    var selectedIndex: NSInteger = 0
    
    var imgDatesArr:[[String:Any]] = AppConstant.customFeelingImgArr
    
    @IBAction func saveBtnAction(_ sender: Any) {
        print("点击btn")
        
        if nameField.text?.count ?? 0 > 4{
            
            SVProgressHUD.showSuccess(withStatus: "不得多于4个字")
            SVProgressHUD.dismiss(withDelay: 1.0) {
                
            }
            return
        }
        
        var imgDict = imgDatesArr[selectedIndex]
        
        if (self.customDict["text"] as? String) == nameField.text && (self.customDict["imgName"] as? String) == (imgDict["imgName"] as? String){ 
            
            //没改变，直接pop
            navigationController?.popViewController(animated: true)
        }else{
            
            var imgArray:[[String:Any]] = UserDefaults.standard.array(forKey: KUSERFeelingImagesArrName ) as! [[String:Any]]
                
            imgDict["isCustom"] = true
            imgDict["text"] = nameField.text

            //检查是否有重名
            for tempDict in imgArray {
                
                if (tempDict["text"] as! String) == (imgDict["text"] as! String){
                    
                    SVProgressHUD.showSuccess(withStatus: "描述不能重复")
                    SVProgressHUD.dismiss(withDelay: 1.0) {
                        
                    }
                    return
                }
            }
            
            if self.customDict["isCustom"] != nil {
                
                imgArray[self.customIndex] = imgDict
                
            }else{
                
                imgArray.insert(imgDict, at: 0)
            }
            
            UserDefaults.standard.setValue(imgArray, forKey: KUSERFeelingImagesArrName)
            UserDefaults.standard.synchronize()
            
            if let delegate = feelingAddDelegate{
                
                delegate.refreshUI()
            }
            
            navigationController?.popViewController(animated: true)
        }
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tfBtmView.layer.borderWidth = 1.0
        tfBtmView.layer.borderColor = UIColor(red: 237.0/255.0, green: 237.0/255.0, blue: 237.0/255.0, alpha: 1.0).cgColor
        tfBtmView.layer.cornerRadius = 10.0
        nameField.delegate = self
        saveBtn.isUserInteractionEnabled = false
        
        
        saveBtn.setTitle("保存", for: .normal)
        saveBtn.layer.borderWidth = 1.0
        saveBtn.layer.borderColor = UIColor.black.withAlphaComponent(0.5).cgColor
        saveBtn.layer.cornerRadius = 23.0
        
        if self.customDict["isCustom"] != nil {
            
            for i in 0..<imgDatesArr.count{
                
                let imgDict = imgDatesArr[i]
                if imgDict["imgName"] as! String ==  customDict["imgName"] as! String{
                    
                    selectedIndex = i
                    break
                }
                
            }
            
            imgView.image = UIImage.init(named: customDict["imgName"] as! String)
            nameField.text = (customDict["text"] as! String)
            saveBtn.isUserInteractionEnabled = true
            saveBtn.setTitleColor(.black, for: .normal)
            
        }else{
            
            let imgDict = imgDatesArr[selectedIndex]
            imgView.image = UIImage.init(named: imgDict["imgName"] as! String)
            
        }
        
        
        self.configCollectionView()
        // Do any additional setup after loading the view.
    }

    func configCollectionView(){
        
        // layout
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: cellSpacing, left: cellSpacing, bottom: cellSpacing, right: cellSpacing)
        layout.minimumLineSpacing = 30
        layout.minimumInteritemSpacing = cellSpacing
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        layout.sectionInset = UIEdgeInsets(top: 10.0, left: 5, bottom: 0, right: 5)
        feelingImgCollectionView.setCollectionViewLayout(layout, animated: false)
        
        feelingImgCollectionView.register(UINib(nibName: reuseIdentifier, bundle: .main), forCellWithReuseIdentifier: reuseIdentifier)
        
        // 设置代理。
        feelingImgCollectionView.delegate = self
        feelingImgCollectionView.dataSource = self
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    
    // MARK: UICollectionViewDataSource, UICollectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgDatesArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cellData = imgDatesArr[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FeelingAddCollectionViewCell
        
        cell.imgView.image = UIImage.init(named: cellData["imgName"] as! String)

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        view.endEditing(true)
        
        selectedIndex = indexPath.item
        let imgDict = imgDatesArr[selectedIndex]
        imgView.image = UIImage.init(named: imgDict["imgName"] as! String)
        
        print("点击了第%d个",indexPath.item)
    }
    
}


extension FeelingAddViewController: UITextFieldDelegate {
    
    func textFieldDidEndEditing(_ textField: UITextField) {

        let string:String = textField.text! as String
        if string.count > 0{
            saveBtn.isUserInteractionEnabled = true
            saveBtn.setTitleColor(.black, for: .normal)
        }else{
            saveBtn.isUserInteractionEnabled = false
            saveBtn.setTitleColor(.lightGray, for: .normal)
        }
        
    }
}

